package main

import (
	_ "GraduationProject/public/tools"
	"github.com/jinzhu/gorm"
	"strconv"

	"GraduationProject/public/tools"
	//"GraduationProject/machine_status/conf"
	"GraduationProject/public/db"
	"GraduationProject/public/models"
	"flag"
	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/mem"
	"log"
	"time"
)

func init() {
	flag.Parse()
	//conf.Init()
	db.ConnectDB()
}

func main() {
	ip := tools.Conf.Get("ip")
	if ip == "" {
		panic("config ip not found")
	}
	var machine models.Machine
	machineID := tools.Conf.Get("machine_id")
	if machineID == "" {
		if err := db.DB.Where("ip = ?", tools.Conf.Get("ip")).
			Last(&machine).Error; err != nil {
			if err == gorm.ErrRecordNotFound {
				machine = models.Machine{
					IP:     ip,
					Status: 1,
				}
				if db.DB.Create(&machine).RowsAffected == 0 {
					panic("创建machine失败")
				}
			} else {
				panic("database error: " + err.Error())
			}
		}
		tools.Conf.Set("machine_id", strconv.Itoa(int(machine.ID)))
		if err := tools.Conf.Save(); err != nil {
			panic("config save error" + err.Error())
		}
	}

	listen()
}

const sleepTime = 10

func listen() {
	for {
		cpuPercent, memoryUsed, totalMemory, err := machineStatus()
		if err != nil {
			log.Printf("machineStatus error: %s\n", err.Error())
			time.Sleep(time.Second * sleepTime)
			continue
		}

		db.DB.Model(&models.Machine{}).
			Where("id = ?", tools.Conf.Get("machine_id")).
			Updates(map[string]interface{}{
				"cpu":          cpuPercent,
				"memory":       memoryUsed,
				"total_memory": totalMemory,
			})

		time.Sleep(time.Second * sleepTime)
	}
}

func machineStatus() (cpuPercent, memoryUsed, totalMemory uint64, err error) {
	percent, err := cpu.Percent(time.Second, false)
	if err != nil {
		return 0, 0, 0, err
	}

	memStat, err := mem.VirtualMemory()
	if err != nil {
		panic(err)
	}

	return uint64(percent[0]), memStat.Used, memStat.Total, nil
}
